<?php

/**
 * @package QFinance\action
 */
class TransactionsImportPanelAction {

    public static $uploadNotRecievedText = 'Upload not recieved';

    /**
     * Read form data and execute import
     * @remotable
     * @upload
     * @formHandler 
     * @param int $bankID Destination bank id
     * @param int $accountID Destination account
     * @param array $file Upload php file information
     * @return ActionResult Action result, where result->temporaryID as temporary id of created transactions
     */
    public function importData($bankID, $accountID, $file) {

        if (is_uploaded_file($file['tmp_name']) && $file['error'] == 0) {
            $importer = ImporterFactory::createImporterFromID($bankID);

            $transactions = $importer->getTransactionsFromFile($file['tmp_name'], $accountID);
            $transactionDAO = DAOFactory::getTransactionDAO();
            $temporaryID = (int) substr((string) time(), 0, 9);

            $transactionDAO->deleteByTemporaryID($temporaryID);

            $validTransactions = array();

            if (sizeof($transactions) > 0) {
                $minDate = null;
                $maxDate = null;

                // Search for oldest and latest transaction date
                foreach ($transactions as $transaction) {
                    if ($minDate == null)
                        $minDate = $transaction->date;
                    else
                        $minDate = min($transaction->date, $minDate);

                    if ($maxDate == null)
                        $maxDate = $transaction->date;
                    else
                        $maxDate = max($transaction->date, $maxDate);
                }

                if ($minDate != null and $maxDate != null) {
                    $existingTransactions = $transactionDAO->queryBetweenDatesAndAccountNotParentAndNotTemporary($minDate, $maxDate, $accountID);
                    if (sizeof($existingTransactions) > 0) {
                        $count = 0;
                        for ($n = 0; $n < count($existingTransactions); $n++) {
                            if (isset($existingTransactions[$n])) {
                                $count2 = 0;
                                foreach ($transactions as $key => $value) {
                                    if ($this->isDuplicateTransaction($existingTransactions[$n], $value)) {
                                        unset($transactions[$key]);
                                    }
                                }
                            }
                            $count++;
                        }
                    }
                }
                $databaseTransaction = new DatabaseTransaction();
                try {
                    foreach ($transactions as $transaction) {
                        // Sets temporaryID
                        $transaction->temporaryID = $temporaryID;
                        // Save to database 
                        $transactionDAO->insert($transaction);
                    }
                    $databaseTransaction->commit();
                } catch (Exception $e) {
                    $databaseTransaction->rollback();
                    throw $e;
                }
            }
        } else {
            throw new Exception(self::$uploadNotRecievedText);
        }

        $return = new ActionResult();
        $return->temporaryID = $temporaryID;

        return $return;
    }

    /**
     * Auxiliar method to verify transaction duplication
     * @param Transaction $transaction1 First comparable transaction
     * @param Transaction $transaction2 Second comparable transaction
     * @return boolean If transactions are equals
     */
    public function isDuplicateTransaction($transaction1, $transaction2) {
        return ($transaction1->date == $transaction2->date &&
        $transaction1->amount == $transaction2->amount &&
        $transaction1->financialNumber == $transaction2->financialNumber &&
        $transaction1->bankMemo == $transaction2->bankMemo);
    }

    /**
     * Make temporary transactions permanent
     * @remotable
     * @param int $temporaryID Transactions temporary ID
     * @return ActionResult Action result
     */
    public function makePermanent($temporaryID) {

        $transactionDAO = DAOFactory::getTransactionDAO();
        $transactionDAO->updateTransactionsTemporaryID($temporaryID, null);

        return new ActionResult();
    }

    /**
     * Remove temporary transactions by id
     * @remotable 
     * @param int $temporaryID Temporary ID
     * @return ActionResult Action result
     */
    public function removeTemporaryTransactions($temporaryID) {

        $transactionDAO = DAOFactory::getTransactionDAO();
        $transactionDAO->deleteByTemporaryID($temporaryID);

        return new ActionResult();
    }

}

?>